
//
//  ForgotPasswordViewController.m
//  OralRobot
//
//  Created by 王桂敏 on 16/4/26.
//  Copyright © 2016年 wangguimin. All rights reserved.
//

#import "ForgotPasswordViewController.h"
#import "UserCenterTextField.h"
#import "Timer.h"
//#import "UserNameModel.h"
#import "ListView.h"

@interface ForgotPasswordViewController ()<TimerDelegate,UITextFieldDelegate,UserCenterTextFieldDelegate>

@property (nonatomic,strong) UserCenterTextField *userNameTF;// 手机号

@property (nonatomic,strong) UserCenterTextField *verificationCodeTF;// 验证码

@property (nonatomic,strong) UserCenterTextField *passwordFirstTF;// 密码

@property (nonatomic,strong) UserCenterTextField *passwordSecondTF;// 确认密码

@property (nonatomic,strong) UIButton *doneButton;//    确定按钮

//@property (nonatomic,strong) UILabel *voiceVerificationCode;//  语音验证码


@end

@implementation ForgotPasswordViewController
{
    BOOL barFixed;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (!barFixed) {
        barFixed = [InstrumentMIssingBar fixMissingBarWithVIewController:self];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initData];
    
    [self initNavigation];
    
    [self initView];
}

#pragma mark - init -
- (void)initNavigation{
    self.title = @"忘记密码";
}

- (void)initData{
    Timer *timer = [Timer defaultTimer];
    timer.delegate = self;
    
}

- (void)initView{
    
    
    //  手机号码
    self.userNameTF = [[UserCenterTextField alloc] initWithFrame:CGRectMake(w(40), h(40), kScreenWidth - w(40) * 2, h(100)) image:nil placeholder:@"请输入您的手机号" keyboardType:UIKeyboardTypeDefault clearButtonMode:UITextFieldViewModeWhileEditing delegate:self userCenterTextFieldDelegate:self];
    self.userNameTF.tag = 502;
    [self.view addSubview:self.userNameTF];
    
    //  验证码
    self.verificationCodeTF = [[UserCenterTextField alloc] initWithFrame:CGRectMake(self.userNameTF.x, getMaxY(self.userNameTF) + h(30), self.userNameTF.width, self.userNameTF.height) image:nil placeholder:@"输入验证码" keyboardType:UIKeyboardTypeDefault clearButtonMode:UITextFieldViewModeWhileEditing delegate:self userCenterTextFieldDelegate:self];
    [self.verificationCodeTF.rightButton setTitle:@"发送验证码" forState:UIControlStateNormal];
    self.verificationCodeTF.rightButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    self.verificationCodeTF.rightButton.titleLabel.font = font(28);
    self.verificationCodeTF.rightButton.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, w(25));
    [self.verificationCodeTF.rightButton setTitleColor:ColorWithHexString(@"2f9be7") forState:UIControlStateNormal];
    [self.verificationCodeTF.rightButton addTarget:self action:@selector(handleVerificationCodeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.verificationCodeTF];
    
    //  密码
    self.passwordFirstTF = [[UserCenterTextField alloc] initWithFrame:CGRectMake(self.userNameTF.x, getMaxY(self.verificationCodeTF) + h(30), self.userNameTF.width, self.userNameTF.height) image:nil placeholder:@"设置新密码" keyboardType:UIKeyboardTypeDefault clearButtonMode:UITextFieldViewModeWhileEditing delegate:self userCenterTextFieldDelegate:self];
    self.passwordFirstTF.isPassword = YES;
    self.passwordFirstTF.secureTextEntry = YES;
    [self.view addSubview:self.passwordFirstTF];
    
    //  确认密码
    self.passwordSecondTF = [[UserCenterTextField alloc] initWithFrame:CGRectMake(self.userNameTF.x, getMaxY(self.passwordFirstTF) + h(30), self.userNameTF.width, self.userNameTF.height) image:nil placeholder:@"确认新密码" keyboardType:UIKeyboardTypeDefault clearButtonMode:UITextFieldViewModeWhileEditing delegate:self userCenterTextFieldDelegate:self];
    self.passwordSecondTF.isPassword = YES;
    self.passwordSecondTF.secureTextEntry = YES;
    [self.view addSubview:self.passwordSecondTF];
    
    
    
    //  确定按钮
    self.doneButton = [UIButton buttonOfImageForNormalWithImage:@"" frame:CGRectMake((kScreenWidth - w(560)) / 2,getMaxY(self.passwordSecondTF) + h(311),self.passwordSecondTF.width,h(90)) target:self action:@selector(handleDoneButtonAction:)];
    [self.doneButton setBackgroundImage:Image(@"button_queding") forState:UIControlStateNormal];
    self.doneButton.imageView.contentMode = UIViewContentModeScaleAspectFill;
    
    [self.view addSubview:self.doneButton];
    
}


#pragma mark - buttonAction -

- (void)handleVerificationCodeButtonAction:(UIButton *)sender{
    
    switch ([[self.userNameTF.text stringByReplacingOccurrencesOfString:@" " withString:@""] isPhone]) {
            
        case PhoneTypeError:
        {
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            __weak typeof(self) weakSelf = self;
            UIAlertAction *doneAction = [UIAlertAction actionWithTitle:@"继续" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                [weakSelf countdown:sender type:VerificationCodeTypeMessage];
            }];
            
            [self showMessageWithTitle:@"警告" message:@"该手机号码有可能获取不到验证码，是否继续尝试？" actionArray:@[cancelAction,doneAction] VC:[UIApplication sharedApplication].keyWindow.rootViewController preferredStyle:UIAlertControllerStyleAlert];
        }
            break;
            
        case PhoneTypeYes:
        {
            [self countdown:sender type:VerificationCodeTypeMessage];
        }
            break;
            
        case PhoneTypeNo:
        {
            [self showWarningWithStatus:@"请输入正确的手机号"];
        }
            break;
            
        default:
            break;
    }
    
}
- (void)countdown:(UIButton *)sender
             type:(VerificationCodeType)type{
    if (sender.isSelected == NO) {
        sender.selected = !sender.selected;
    }
    
    if (sender.isSelected == YES) {
        
        if ([[[sender titleForState:UIControlStateSelected] stringByReplacingOccurrencesOfString:@"秒" withString:@""] integerValue] > 0) {
            [self showWarningWithStatus:@"验证码已发送，请稍后重试"];
            
        } else {
            
            [self initNetWorkOfVerificationCodeWithType:type];
        
            [UIView animateWithDuration:1 animations:^{

                [sender setTitle:@"60秒" forState:UIControlStateSelected];
                [sender setTitleColor:ColorWithHexString(@"cfdfe8") forState:UIControlStateNormal];
                
            } completion:^(BOOL finished) {
            }];
            
        }
    }
    
}

- (void)handleDoneButtonAction:(UIButton *)sender{
    
    if (!sender.isSelected) {
        if ([[self.userNameTF.text stringByReplacingOccurrencesOfString:@" " withString:@""] isPhone] == PhoneTypeNo) {
            
            [self showWarningWithStatus:@"请检查手机号是否符合要求"];
            
        }else if (![self.verificationCodeTF.text isVerificationCode]){
            
            [self showWarningWithStatus:@"请检查验证码是否符合要求"];
            
        } else if (![self.passwordFirstTF.text isPassword]){
            
            [self showWarningWithStatus:@"请检查密码是否符合要求"];
            
        } else{
            
            [self showWarningWithStatus:@"请检查两次密码是否输入相同"];
        }
    } else {
        if ([[self.userNameTF.text stringByReplacingOccurrencesOfString:@" " withString:@""] isPhone] == PhoneTypeError) {
            
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            __weak typeof(self) weakSelf = self;
            UIAlertAction *doneAction = [UIAlertAction actionWithTitle:@"继续" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                [weakSelf initNetWork];
            }];
            
            [self showMessageWithTitle:@"警告" message:@"该手机号码有可能修改失败，是否继续尝试？" actionArray:@[cancelAction,doneAction] VC:[UIApplication sharedApplication].keyWindow.rootViewController preferredStyle:UIAlertControllerStyleAlert];
            
            
        } else {
            [self initNetWork];
        }

    }
    
}

#pragma mark - TimerDelegate -
- (void)timer:(Timer *)timer{
    if (self.verificationCodeTF.rightButton.isSelected && [[[self.verificationCodeTF.rightButton titleForState:UIControlStateSelected] stringByReplacingOccurrencesOfString:@"秒" withString:@""] integerValue] > 0) {
        [self.verificationCodeTF.rightButton setTitle:[NSString stringWithFormat:@"%d秒",[[self.verificationCodeTF.rightButton titleForState:UIControlStateSelected] integerValue] - 1] forState:UIControlStateSelected];
    } else if (self.verificationCodeTF.rightButton.isSelected && [[self.verificationCodeTF.rightButton titleForState:UIControlStateSelected] integerValue] == 0){
        self.verificationCodeTF.rightButton.selected = !self.verificationCodeTF.rightButton.selected;
        @weakify(self);
        [UIView animateWithDuration:1 animations:^{
            @strongify(self);
            [self.verificationCodeTF.rightButton setTitle:@"发送验证码" forState:UIControlStateSelected];
            [self.verificationCodeTF.rightButton setTitleColor:ColorWithHexString(@"2f9be7") forState:UIControlStateNormal];
        } completion:^(BOOL finished) {
        }];
        
    }
}
#pragma mark - UserCenterTextFieldDelegate -
- (void)textFieldDidChange:(UserCenterTextField *)textField{
    
    if ([[self.userNameTF.text stringByReplacingOccurrencesOfString:@" " withString:@""] isPhone] != PhoneTypeNo && [self.passwordFirstTF.text isPassword] && [self.passwordSecondTF.text isEqualToString:self.passwordFirstTF.text] && [self.verificationCodeTF.text isVerificationCode]) {
        self.doneButton.selected = YES;
    } else {
        self.doneButton.selected = NO;
    }
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.view endEditing:YES];
    return YES;
}

#pragma mark - UITextFieldDelegate -

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField.tag == 502) {
        
        return [UITextField phoneWithBlank:textField range:range replacementString:string];
    } else {
        
        return YES;
    }
}
#pragma mark - touchesBegan -
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

#pragma mark - network and networkDelegate -


- (void)initNetWorkOfVerificationCodeWithType:(VerificationCodeType)type{
    
    NSMutableDictionary *paramsOfVerificationCode = [NSMutableDictionary dictionary];
    
    switch (type) {
        case VerificationCodeTypeMessage:
        {
            paramsOfVerificationCode[@"verifySendType"] = @"0";
        }
            break;
            
        case VerificationCodeTypeVoice:
        {
            paramsOfVerificationCode[@"verifySendType"] = @"1";

        }
            break;
            
        default:
            break;
    }
    
    paramsOfVerificationCode[@"mobile"] = [[self.userNameTF.text stringByReplacingOccurrencesOfString:@" " withString:@""] isEmpty] ? @"" : [self.userNameTF.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    paramsOfVerificationCode[@"type"] = @"D";
    
    [self.manager postWithURL:NET_VERFICATIONCODE param:paramsOfVerificationCode delegate:self isEncrypt:YES type:NetWorkingType1];
}


- (void)initNetWork{
    self.params[@"mobile"] = [self.userNameTF.text.length ? self.userNameTF.text:@""stringByReplacingOccurrencesOfString:@" " withString:@""];
     self.params[@"password"] = self.passwordFirstTF.text;
    
    self.params[@"verificationCode"] = self.verificationCodeTF.text;
    self.params[@"type"] = @"1";

    [self.manager postWithURL:NET_FORGETPASSWORD param:self.params delegate:self isEncrypt:YES type:NetWorkingType0];
}

- (void)networkingHandleSuccess:(NetworkingHandle *)handle parameters:(NSDictionary *)parameters responseObject:(id)responseObject type:(NetWorkingType)type{

    switch (type) {
        case NetWorkingType0:
        {
            
//            [self setPassword:self.passwordUpTF.text];
            
            [self showSuccessWithStatus:@"新密码设置成功，请重新登录"];
            
            [self handleLeftButtonAction:nil];
            
        }
            break;
        case NetWorkingType1:// 验证码
        {
            [self showSuccessWithStatus:@"验证码发送成功"];
        }
            break;
            

            
        default:
            break;
    }
}

- (void)networkingHandlefail:(NetworkingHandle *)handle type:(NetWorkingType)type{
    
}

- (void)networkingHandleWarning:(NetworkingHandle *)handle responseObject:(id)responseObject type:(NetWorkingType)type{
    

    
}





/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
